package com.example.rxjava.ui

import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.WindowInsets
import android.view.WindowInsetsController
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.example.rxjava.R
import com.example.rxjava.extend.setRoundBackground
import com.example.rxjava.extend.toast
import com.example.rxjava.utils.DataStoreManager
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.ObservableOnSubscribe
import io.reactivex.rxjava3.core.Observer
import io.reactivex.rxjava3.disposables.Disposable
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.concurrent.TimeUnit


class MainActivity : AppCompatActivity() {
    private lateinit var scope: CoroutineScope

    private var windowController: WindowInsetsController? = null

    private val array = arrayOf(1, 2, 5, 8, 0)
    private val TAG = "RXJAVA"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        tvTest1.setRoundBackground(Color.WHITE, radiu = 10f, strokeColor = Color.RED, strokeWidth = 1)
        tvMap.setRoundBackground(radiu = 50f, strokeColor = Color.GREEN, strokeWidth = 1)
        tvObservable.setRoundBackground(radiu = 50f, strokeColor = Color.RED, strokeWidth = 1)

        scope = CoroutineScope(Dispatchers.Main)
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.R) {
            windowController = tvMap.windowInsetsController
        }

        tvTest1.setOnClickListener {
            start()
        }
        tvMap.setOnClickListener {
            toast("测试map操作符")
            useMap()
        }
        tvObservable.setOnClickListener {
            createObservable()
        }
        tvDataStore.setOnClickListener {
            scope.launch {
                DataStoreManager.get().saveString("data_main", "jack")
            }
            val intent = Intent(this, SecondActivity::class.java)
            startActivityForResult(intent, 100)
        }
        Glide.with(this)
            .load(R.mipmap.ic_launcher)
            .into(image)
        hideNarbar()
    }

    private fun createObservable() {
        Log.e(TAG, "第一种方式：just")
        Observable.just("1", "2", "3")
            .subscribe(object: Observer<String> {
                override fun onComplete() {
                    Log.e(TAG, "just --> onComplete")
                }

                override fun onSubscribe(d: Disposable?) {

                }

                override fun onNext(t: String?) {
                    Log.e(TAG, t ?: "")
                }

                override fun onError(e: Throwable?) {

                }

            })
        Log.e(TAG, "range创建")
        Observable.range(array[0], array.size)
            .subscribe { num ->
                Log.e(TAG, "item$num")
            }
        Log.e(TAG, "range创建")
        Observable.fromIterable(array.toList())
            .subscribe(object: Observer<Int> {

                override fun onComplete() {
                    Log.e(TAG, "onComplete")
                }

                override fun onSubscribe(d: Disposable?) {

                }

                override fun onNext(t: Int?) {
                    Log.e(TAG, "from$t")
                }

                override fun onError(e: Throwable?) {

                }

            })
        Log.e(TAG, "scan的使用")
        Observable.just(1, 3, 5, 7, 9)
            .scan { t1: Int, t2: Int ->
                return@scan if (t2 == 5) t1 + t2 else t2
            }
            .subscribe(object: Observer<Int> {
                override fun onComplete() {

                }

                override fun onSubscribe(d: Disposable?) {

                }

                override fun onNext(t: Int?) {
                    Log.e(TAG, "result=$t")
                }

                override fun onError(e: Throwable?) {

                }

            })
    }

    private fun useMap() {
        Observable.create(ObservableOnSubscribe<Int> { emitter ->
            array.forEach {
                emitter?.onNext(it)
            }
            try {
                emitter?.onComplete()
            } catch (e: Exception) {
                emitter?.onError(e)
            }
        })
            .map {
                return@map "item$it"
            }
            .subscribe(object: Observer<String> {

                override fun onComplete() {

                }

                override fun onSubscribe(d: Disposable?) {

                }

                override fun onNext(t: String?) {
                    Log.e("RXJAVA", t ?: "")
                }

                override fun onError(e: Throwable?) {

                }

            })
    }

    private fun start() {
        Observable
            .interval(0,1000, TimeUnit.MILLISECONDS)
            .take(5)
            .map {
                return@map it + 1
            }
            .subscribe {
                Log.e("num", "num=$it")
            }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        scope.launch {
            val data = DataStoreManager.get().getString("data_second")
            withContext(Dispatchers.Main) {
                toast(data)
            }
        }
    }

    private fun hideNarbar() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
            //控制底部虚拟键盘
            window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                    or View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                    or View.SYSTEM_UI_FLAG_IMMERSIVE)
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
        } else {
            //隐藏状态栏
            windowController?.hide(WindowInsets.Type.statusBars())
            //隐藏虚拟按键
            windowController?.hide(WindowInsets.Type.navigationBars())
        }
    }
}